#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./paas/esb/apps/manager/channel/forms.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import re
from django import forms
from esb.bkcore.models import ESBChannel, ComponentSystem

class ESBChannelForm(forms.ModelForm):
    """Form for ESBChannel"""
    TYPE_CHOICE = (
     (1, u'执行API'),
     (2, u'查询API'))
    component_system = forms.ModelChoiceField(label=u'所属组件系统', queryset=ComponentSystem.objects.all(), required=True, empty_label=None)
    path = forms.RegexField(label=u'通道路径', max_length=255, required=True, regex='^/[/a-zA-Z0-9_-]+$', help_text=u'通道路径，以斜杠开头，只能包含斜杠、字母、数字、下划线(_)、连接符(-)，一般设置为"/system_name/component_name/"，例如"/host/get_host_list/"；通道路径需唯一', error_messages={'invalid': u'输入的通道路径不符合要求'
       })
    component_codename = forms.RegexField(label=u'对应组件代号', max_length=255, required=True, regex='^[a-z][a-z0-9._]+[a-z0-9_]$', help_text=u'组件代号，只能包含小写字母、数字、下划线或点号，由三部分组成："前缀(generic).系统名小写.组件模块名小写"，例如 "generic.host.get_host_list"', error_messages={'invalid': u'输入的组件代号不符合要求'
       })
    timeout_time = forms.IntegerField(label=u'超时时长', required=False, error_messages={'invalid': u'输入格式不正确'
       }, min_value=1, max_value=86400, initial=None, help_text=u'单位秒，未设置时以所属组件系统超时时长为准', widget=forms.NumberInput(attrs={'style': 'width: 450px;'}))
    type = forms.ChoiceField(label=u'组件类型', choices=TYPE_CHOICE, required=True, initial=2)

    class Meta:
        model = ESBChannel
        fields = [
         'component_system', 'name', 'path', 'component_codename',
         'is_active', 'timeout_time', 'type', 'comp_conf']

    def clean_name(self):
        component_system = self.cleaned_data.get('component_system')
        name = self.cleaned_data['name'].strip()
        if not component_system:
            return name
        if ESBChannel.objects.filter(component_system=component_system, name=name).exists():
            raise forms.ValidationError(u'系统【%s】下，通道名称已存在' % component_system.name)
        return name

    def clean_path(self):
        path = self.cleaned_data['path']
        path = '/%s/' % path.strip('/')
        if ESBChannel.objects.filter(path=path).exists():
            raise forms.ValidationError(u'通道路径已存在')
        return path

    def clean_component_codename(self):
        component_codename = self.cleaned_data['component_codename']
        component_system = self.cleaned_data.get('component_system')
        if not component_system:
            return component_codename
        if not re.match('^generic\.%s\.[a-z][a-z0-9_]*$' % component_system.name.lower(), component_codename):
            raise forms.ValidationError(u'输入的组件代号不符合要求')
        return component_codename

    def clean(self):
        data = self.cleaned_data
        for key, val in data.iteritems():
            if isinstance(val, basestring):
                data[key] = val.strip()

        return data


class EditESBChannelForm(ESBChannelForm):

    def clean_name(self):
        component_system = self.cleaned_data.get('component_system')
        name = self.cleaned_data['name'].strip()
        if not component_system:
            return name
        if ESBChannel.objects.exclude(id=self.instance.id).filter(component_system=component_system, name=name).exists():
            raise forms.ValidationError(u'系统【%s】下，通道名称已存在' % component_system.name)
        return name

    def clean_path(self):
        path = self.cleaned_data['path']
        path = '/%s/' % path.strip('/')
        if ESBChannel.objects.exclude(id=self.instance.id).filter(path=path).exists():
            raise forms.ValidationError(u'通道路径已存在')
        return path
